package org.itboys.mobile.service.mongo.front.dynamic;

import org.itboys.admin.entity.lasted.SundayUpload;
import org.itboys.admin.service.lasted.SundayUploadService;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dto.dynamic.SundayDynamicDto;
import org.itboys.mobile.dto.dynamic.SundayDynamicOperateDto;
import org.itboys.mobile.dto.dynamic.SundayDynamicProductDto;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.mongo.dynamic.SundayDynamic;
import org.itboys.mobile.entity.mongo.dynamic.SundayDynamicOperate;
import org.itboys.mobile.entity.mongo.dynamic.SundayDynamicProduct;
import org.itboys.mobile.entity.mysql.order.SundayOrderProduct;
import org.itboys.mobile.service.mongo.front.SundayFrontCollectionService;
import org.itboys.mobile.service.mongo.front.SundayFrontMemberService;
import org.itboys.mobile.util.NameUtil;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.itboys.param.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：jiangxiong
 * 日期：2017年4月26日
 * 联系方式 ：empty90911@126.com
 * 描述：圣代_移动端（通用）_动态_sevice。如果属性不够，请自行填充
 */
@Service
public class SundayFrontDynamicService extends BaseMongoService<SundayDynamic>{

    @Resource(name = "mobileDs")
    private MongoDataSource sundayDataSource;
    @Override
    protected MongoDataSource getMongoDataSource() {
        return sundayDataSource;
    }

    @Override
    protected Class<SundayDynamic> getEntityClass() {
        return SundayDynamic.class;
    }

    @Autowired
    private SundayFrontMemberService memberService;
    @Autowired
    private SundayFrontDynamicProductService dynamicProductService;
    @Autowired
    private SundayFrontDynamicOperateService dynamicOperateService;
    @Autowired
    private SundayFrontCollectionService collectionService;
    @Autowired
    private SundayUploadService uploadService;
    @Autowired
    private ResourceHolder resourceHolder;
    /**
     * 生成达人试用动态，评论达人试用后生成
     * @param memberId

     * @param content
     * @param orderProducts
     * @param images
     */
    public void saveShiYong(Long memberId,String content,List<SundayOrderProduct> orderProducts,List<String> images){
        SundayDynamic dynamic = new SundayDynamic();
        dynamic.setType(2);
        dynamic.setMemberId(memberId);
        SundayMember member=memberService.getById(memberId);
        dynamic.setMemberName(member.getNickName());
        dynamic.setMemberImage(member.getImage());
        dynamic.setDzNumber(0);
        dynamic.setPlNumber(0);
        dynamic.setContent(content);
        super.save(dynamic);
        //保存商品
        List<SundayDynamicProduct> dynamicProducts = new ArrayList<>();
        for(SundayOrderProduct orderProduct:orderProducts){
            dynamicProducts.add(new SundayDynamicProduct(dynamic.getId(), orderProduct.getProductId(), orderProduct.getName(), orderProduct.getImage(), orderProduct.getPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString()));
        }
        if(ListUtil.isNotNull(dynamicProducts)){
            dynamicProductService.batchSaveWithoutLogin(dynamicProducts);
        }
        //保持动态的图片
        List<SundayUpload> uploadImages = new ArrayList<>();
        for(String image:images){
            if(!image.equalsIgnoreCase("noImage")){
                uploadImages.add(new SundayUpload(dynamic.getId(), SundayDynamic.class.getSimpleName(),
                        image, "动态"+dynamic.getId()+"图片", null, null)) ;
            }

        }
        if(ListUtil.isNotNull(dynamicProducts)){
            uploadService.batchSaveWithoutLogin(uploadImages);
        }
    }


    /**
     * 生成本地爱购动态
     * @param memberId
     * @param orderProducts
     * @param cityId
     * @param cityName
     * @param provinceId
     * @param provinceName
     */
    public void saveLocal(Long memberId, List<SundayOrderProduct> orderProducts, Long cityId, String cityName,Long provinceId,String provinceName){
        SundayDynamic dynamic = new SundayDynamic();
        dynamic.setType(3);
        dynamic.setMemberId(memberId);
        SundayMember member=memberService.getById(memberId);
        dynamic.setMemberName(member.getNickName());
        dynamic.setMemberImage(member.getImage());
        dynamic.setDzNumber(0);
        dynamic.setPlNumber(0);
        dynamic.setContent("购买了如下商品");
        dynamic.setProvinceId(provinceId);
        dynamic.setProvinceName(provinceName);
        dynamic.setCityId(cityId);
        dynamic.setCityName(cityName);
        super.save(dynamic);
        //保存商品
        List<SundayDynamicProduct> dynamicProducts = new ArrayList<>();
        for(SundayOrderProduct orderProduct:orderProducts){
            dynamicProducts.add(new SundayDynamicProduct(dynamic.getId(), orderProduct.getProductId(), orderProduct.getName(), orderProduct.getImage(), orderProduct.getPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString()));
        }
        if(ListUtil.isNotNull(dynamicProducts)){
            dynamicProductService.batchSaveWithoutLogin(dynamicProducts);
        }


    }

    /**
     * 点赞或评论
     * @param dynamicId
     * @param type 1,点赞，2评论
     * @param content
     */
    public void operate(Long dynamicId,Long memberId,Integer type,String content){
        //修改动态主体的点赞和评论数量
        SundayDynamic dynamic = super.getById(dynamicId);
        if(type==1){
            dynamic.setDzNumber(dynamic.getDzNumber()+1);
        }else if(type==2){
            dynamic.setPlNumber(dynamic.getPlNumber()+1);
        }
        super.updateExceptEmpty(dynamicId,dynamic);
        //增减动态的评论或点赞记录
        SundayDynamicOperate dynamicOperate = new SundayDynamicOperate();
        dynamicOperate.setDynamicId(dynamicId);
        dynamicOperate.setType(type);
        dynamicOperate.setMemberId(memberId);
        SundayMember member=memberService.getById(memberId);
        dynamicOperate.setMemberName(member.getNickName());
        dynamicOperate.setMemberImage(member.getImage());
        dynamicOperate.setContent(content);
        dynamicOperateService.saveWithoutLogin(dynamicOperate);
    }

    /**
     * 获取动态
     * @param request
     * @param type 2，达人试用，3，本地爱购，4，特别关注
     * @param memberId
     */
    public List<SundayDynamicDto> selectDynamic(HttpServletRequest request, Long memberId, Integer type){
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("sort","ct");
        param.put("order","DESC");
        //达人试用
        if(type==2){
            param.put("type",2);
        }else if(type==3){
            param.put("type",3);
            //解析IP所在城市匹配对应的数据。暂时只开放绵阳。后续配合商务谈判
        //特别关注
        }else if(type==4){
           List<Long> memberIds= collectionService.selectCollection(memberId,SundayCommonConstants.collection_type_member);
           param.put("memberId in",memberIds);
        }
        PageResult<SundayDynamic> pageResult=super.pageQuery(request,param);
        //组装DTO
        List<SundayDynamicDto> dtos = packageBatch(memberId,pageResult.getData());

       return dtos;
    }
    /**
     * 获取动态
     * @param request
     * @param type 2，达人试用，3，本地爱购，4，特别关注
     * @param memberId
     */
    /**
     * 获取动态详情
     * @param dynamicId
     * @param memberId
     * @return
     */
    public SundayDynamicDto detail(Long dynamicId, Long memberId){
        SundayDynamic dynamic = super.getById(dynamicId);
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("dynamicId",dynamic.getId());
        List<SundayDynamicProduct> allProducts=dynamicProductService.list(param);
        List<SundayDynamicOperate> allOperates=dynamicOperateService.list(param);
        param.clear();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("outClassId",dynamic.getId());
        param.put("outClassName",SundayDynamic.class.getSimpleName());
        List<SundayUpload> allImages=uploadService.list(param);
        List<SundayDynamicOperate> allComments=allOperates;

        SundayDynamicDto dto= packageSingle(memberId,
                    dynamic,
                    allProducts,
                    allOperates,
                    allImages,
                    allComments
        );

        return dto;
    }
    /**
     * 获取个人中心,不分页
     * @param request
     * @param memberId
     * @param personId
     * @return
     */
    public Map<String,Object> selectDynamicByPerson(HttpServletRequest request,Long memberId, Long personId){
        Map<String,Object> result = new HashMap<String,Object>();
       // int isCollection = 0;
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("sort","ct");
        param.put("order","DESC");
        param.put("memberId",personId);
        List<SundayDynamicDto> dtos=packageBatch(memberId,super.list(param));
        //判断是否收藏
        int isCollection = collectionService.checkIsCollection(memberId,SundayCommonConstants.collection_type_member,personId);
        result.put("dynamics",dtos);
        result.put("isCollection",isCollection);
        //个人信息
        String imgRoot = resourceHolder.getStringValue("imgRoot");
        SundayMember person=memberService.getById(personId);
        result.put("memberId",person.getId());
        result.put("memberName",person.getNickName());
        result.put("memberImage",imgRoot+person.getImage());


        return result;
    }

    /**
     * 单个组装DTO
     * @param dynamic
     * @param allProducts
     * @param allOperates
     * @param allImages
     * @param allComments
     * @param allComments
     * @return
     */
    public SundayDynamicDto packageSingle(
                                          Long memberId,
                                          SundayDynamic dynamic,
                                          List<SundayDynamicProduct> allProducts,
                                          List<SundayDynamicOperate> allOperates,
                                          List<SundayUpload> allImages,
                                          List<SundayDynamicOperate> allComments
                                          ){
        String imgRoot = resourceHolder.getStringValue("imgRoot");
        SundayDynamicDto dto = new SundayDynamicDto(dynamic.getId(),dynamic.getCreateTime(),dynamic.getCreateDate());
       // dto.setId(dynamic.getId());
        dto.setType(dynamic.getType());
        dto.setMemberId(dynamic.getMemberId());
        dto.setMemberName(dynamic.getMemberName());
        dto.setMemberImage(imgRoot+dynamic.getMemberImage());
        dto.setContent(dynamic.getContent());
        dto.setCityName(dynamic.getCityName());
        dto.setDzNumber(dynamic.getDzNumber());
        dto.setPlNumber(dynamic.getPlNumber());
        //组装动态产品
        if(ListUtil.isNotNull(allProducts)){
            List<SundayDynamicProductDto> products = new ArrayList<>();
            for(SundayDynamicProduct product:allProducts){
                if(LongUtil.isNotZreo(product.getDynamicId())&&
                        product.getDynamicId().longValue()==dynamic.getId()){
                    products.add( new SundayDynamicProductDto(product.getProductId(),product.getCreateTime(),product.getCreateDate(),
                            product.getName(),product.getImage(),product.getPrice()));
                }
            }
            dto.setProducts(products);
        }


        //组装动态点赞或评论数量
        if(ListUtil.isNotNull(allOperates)) {

            int dzNumber = 0;
            int plNumber = 0;

            for (SundayDynamicOperate operate : allOperates) {
                if (LongUtil.isNotZreo(operate.getDynamicId()) &&
                        operate.getDynamicId().longValue() == dynamic.getId()) {
                    if (operate.getType() == 1) {
                        dzNumber++;
                    } else if (operate.getType() == 2) {
                        plNumber++;
                    }


                }
            }

            int isDz = 0;//是否点赞
            for (SundayDynamicOperate operate : allOperates) {
                if (LongUtil.isNotZreo(operate.getDynamicId()) &&
                        LongUtil.isNotZreo(operate.getMemberId())&&
                        operate.getDynamicId().longValue() == dynamic.getId()&&
                        operate.getType() == 1&&operate.getMemberId().longValue()==memberId.longValue()) {
                    isDz=1;
                    break;
                }
            }
            dto.setDzNumber(dzNumber);
            dto.setPlNumber(plNumber);
            dto.setIsDz(isDz);


        }
        //组装图片
        if(ListUtil.isNotNull(allImages)) {
            List<String> images = new ArrayList<>();
            for (SundayUpload image : allImages) {
                if (LongUtil.isNotZreo(image.getOutClassId()) &&
                        image.getOutClassId().longValue() == dynamic.getId() &&
                        image.getOutClassName().equalsIgnoreCase(SundayDynamic.class.getSimpleName())) {
                    images.add(imgRoot + image.getSavePath());
                }
            }
            dto.setImages(images);
        }
        //组装对应的评论
        if(ListUtil.isNotNull(allComments)) {
            List<SundayDynamicOperateDto> comments = new ArrayList<>();
            for (SundayDynamicOperate comment : allComments) {
                if (LongUtil.isNotZreo(comment.getDynamicId()) &&
                        comment.getDynamicId().longValue() == dynamic.getId()) {
                    if (comment.getType() == 2) {
                       comments.add( new SundayDynamicOperateDto(
                               comment.getId(),comment.getCreateTime(),comment.getCreateDate(),
                               comment.getMemberId(),comment.getMemberName(),imgRoot+comment.getMemberImage(),comment.getContent()));
                    }
                }
            }
            dto.setComments(comments);
        }


        return dto;
    }

    /**
     * 批量组装DTO,
     * @param dynamics
     * @return
     */
    public List<SundayDynamicDto> packageBatch(Long memberId,List<SundayDynamic> dynamics){
        List<SundayDynamicDto> dtos = new ArrayList<>();
        List<Long> dynamicIds = new ArrayList<>();

        for(SundayDynamic dynamic:dynamics){
            dynamicIds.add(dynamic.getId());
        }

        if(ListUtil.isNotNull(dynamicIds)){
            Map<String,Object> param = new HashMap<String,Object>();
            param.put("isDeleted",SundayCommonConstants.NO);
            param.put("dynamicId in",dynamicIds);
            List<SundayDynamicProduct> allProducts=dynamicProductService.list(param);
            List<SundayDynamicOperate> allOperates=dynamicOperateService.list(param);
            param.clear();
            param.put("isDeleted",SundayCommonConstants.NO);
            param.put("outClassId in",dynamicIds);
            param.put("outClassName",SundayDynamic.class.getSimpleName());
            List<SundayUpload> allImages=uploadService.list(param);
            List<SundayDynamicOperate> allComments=allOperates;
            for(SundayDynamic dynamic:dynamics){
                dtos.add(packageSingle(memberId,
                        dynamic,
                       allProducts,
                       allOperates,
                        allImages,
                        allComments
                ));
            }
        }


        return dtos;
    }


}
